﻿@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Index_Layout.cshtml";
    ViewFWUser currentUserInfo = base.Context.Session.GetUserInfo();
}

@if (!currentUserInfo.IsHaveRights("FW_Company", "00"))
{
    throw new Exception(@L("您没有该页面的权限"));
}

@section styles{
    <link href="~/lib/YdmJUI/static/plugins/ueditorAPP/xiumi-ue-v5.css" rel="stylesheet" />
}
@section scripts{
    @*<script src="~/js/views/Main/Home/index.js" asp-append-version="true"></script>*@
    <script src="~/lib/vue/vue.min.js"></script>
    <script src="~/lib/YdmJUI/static/plugins/ueditorAPP/ueditor.config.js"></script>
    <script src="~/lib/YdmJUI/static/plugins/ueditorAPP/ueditor.all.min.js"></script>
    <script src="~/lib/YdmJUI/static/plugins/ueditorAPP/xiumi-ue-dialog-v5.js"></script>
}

<div data-toggle="topjui-layout" data-options="fit:true">
    @*<div data-options="region:'north',title:'@L("查找")',split:true" style="height:150px;padding-left:10px">
            <form id="mySearchForm" style="display:none">
                <table style="width:100%;border-collapse:separate; border-spacing:0px 10px;">
                    <tr>

                        <td class="label">@L("企业名称")</td>
                        <td>
                            <input id="mySearchFormCompanyName" type="text"  data-toggle="topjui-textbox" data-name="companyName" data-op="like"  data-datatype="nvarchar" data-options="width:250">
                        </td>

                        <td class="label">@L("企业介绍")</td>
                        <td>
                            <input id="mySearchFormCompanyDesc" type="text"  data-toggle="topjui-textbox" data-name="companyDesc" data-op="like"  data-datatype="nvarchar" data-options="width:250">
                        </td>

                        <td class="label">@L("企业Logo")</td>
                        <td>
                            <input id="mySearchFormCompanyLogoUrl" type="text"  data-toggle="topjui-textbox" data-name="companyLogoUrl" data-op="like"  data-datatype="nvarchar" data-options="width:250">
                        </td>

                    </tr>
                </table>
                <div style="position:absolute;right:20px; bottom:10px;">
                  <a href="javascript:void(0)" data-toggle="topjui-linkbutton" data-options="iconCls:'fa fa-search-minus', btnCls:'topjui-btn-search'" onclick="searchQuery()">@L("搜索(enter)")</a>
                    <a href="javascript:void(0)" data-toggle="topjui-linkbutton" data-options="iconCls:'fa fa-mail-reply', btnCls:'topjui-btn-clear'" onclick="$('#mySearchForm').iForm('clear')">@L("清空(esc)")</a>
                </div>
            </form>
        </div>*@

    <div data-options="region:'center',title:'',fit:false,split:true,border:false">
        <table id="myDg"></table>

        <div id="myDg-toolbar" class="topjui-toolbar" data-options="
        grid:{
            type:'datagrid',
            id:'myDg'
            }">
            <!--如果要需要在列头加查询那么需要加上 style="height:72px;display:block" 样式 -->

            @if (currentUserInfo.IsHaveRights("FW_Company", "01") && base.Context.Request.Query["mode"] != "3")
            {
                <a id="add" href="javascript:void(0)" data-toggle="topjui-menubutton"
                   data-options="iconCls:'fa fa-plus',onClick: oepnAddDiag">
                    @L("新增")
                </a>
            }

            @* @if (currentUserInfo.IsHaveRights("FW_Company", "91") && base.Context.Request.Query["mode"]!="3")
                {
                        <a href="javascript:void(0)"
                        data-toggle="topjui-menubutton"
                        data-options="
                        method:'import',
                        extend: '#myDg-toolbar',
                        iconCls:'fa fa-cloud-upload',
                        btnCls:'topjui-btn-blue',
                        exportTemplateUrl:'/api/services/app/File/DownFile?type=FW_Company',
                        uploadUrl:'/api/services/app/File/UploadFileNew?type=FW_Company',
                        tableName:'FW_Company',
                        url:'/api/services/app/FWCompany/ImportExcel'">@L("导入")
                       </a>
                }*@

            @if (currentUserInfo.IsHaveRights("FW_Company", "02"))
            {
                @*<a id="add" href="javascript:void(0)" data-toggle="topjui-menubutton"
                        data-options="iconCls:'fa fa-pencil',btnCls:'topjui-btn-blue',onClick: openEditDiag">
                        @L("编辑")
                    </a>*@
            }

            @if (currentUserInfo.IsHaveRights("FW_Company", "03"))
            {
                <a href="javascript:void(0)" data-toggle="topjui-menubutton" data-options="
                    method:'doAjax',
                    btnCls:'topjui-btn-delete',
                    extend: '#myDg-toolbar',
                    iconCls:'fa fa-trash',
                    confirmMsg:'@L("确定删除选中的数据吗")?',
                    grid: {uncheckedMsg:'@L("请勾选要删除的数据")',param:'id:id'},
                    url:'/api/services/app/FWCompany/BatchDelete' ">
                    @L("删除")
                </a>
            }

            <a href="javascript:void(0)"
               data-toggle="topjui-menubutton"
               data-options="
                method:'filter',
                extend: '#myDg-toolbar',
                btnCls:'topjui-btn-filter'">
                @L("过滤")
            </a>

            <a href="javascript:void(0)"
               data-toggle="topjui-menubutton"
               data-options="
                   method:'search',
                   extend: '#myDg-toolbar' ,
                   btnCls:'topjui-btn-query'">
                @L("查询")
            </a>

            @if (currentUserInfo.IsHaveRights("FW_Company", "92"))
            {
                <a href="javascript:void(0)"
                   data-toggle="topjui-menubutton"
                   data-options="
                    method:'export',
                    extend: '#myDg-toolbar',
                    iconCls:'fa fa-cloud-download',
                    btnCls:'topjui-btn-export',
                    url:'/api/services/app/FWCompany/GetGridExcel'">
                    @L("导出")
                </a>
            }

            <a href="javascript:void(0)"
               data-toggle="topjui-menubutton"
               data-options="
                 btnCls:'topjui-btn-black',
                 onClick:setRight">@L("设置权限")</a>


                @*<a href="javascript:void(0)"
                        data-toggle="topjui-menubutton"
                        data-options="
                            btnCls:'topjui-btn-black',
                            onClick:myQuery">@L("自定义方法")
                    </a>*@

                <!--添加queryForm-->
                @*<hr style="margin: 3px 0">
                    <form id="myQueryForm" class="search-box" style="float:left">
                        <span>
                            <label>任务状态</label>
                            <input type="text"
                                   data-toggle="topjui-combobox"
                                   value="1"
                                   data-name="taskStatus"
                                   data-op="eq"
                                   data-datatype="int"
                                   data-options="
                                       data:[{value:1,text:'进行中'},{value:2,text:'已结束'},{value:'',text:'全部'}],
                                       width:150,
                                       panelHeight:150">
                        </span>
                       <a href="javascript:void(0)" data-toggle="topjui-linkbutton" data-options="iconCls:'fa fa fa-search',btnCls:'topjui-btn-search'" onclick="searchQuery()">@L("搜索(enter)")</a>
                        <a href="javascript:void(0)" data-toggle="topjui-linkbutton" data-options="iconCls:'fa fa-mail-reply',btnCls:'topjui-btn-clear'" onclick="$('#myQueryForm').iForm('clear')">@L("清空(esc)")</a>
                    </form>*@
            </div>
        </div>
    </div>

<!--自定义修改,尽量不要改框架的代码,修改全放这里,如果要修改框架代码,尽量在这里写个方法,在框架调用-->
<script>
    var fWCompanyIndex={
        queryObj: $.dm.getQueryObj(), // URL的参数
        buInfo: $.dm.getBuInfo(), // 门店信息
        userInfo: $.dm.getUserInfo(), // 用户信息
        appInfo:$.dm.getAppInfo(), // 系统信息
        selfClick:function (){ // 自定义按钮对应的方法
            alert("123");
            // 选择一行
            $('#myDg').datagrid('selectRow', 1);
            // 提示信息
            //$.iMessager.alert('自定义方法', '自定义方法被执行了！', 'messager-info');

            //var checkedRows = $('#productDg').iDatagrid('getChecked');
            //console.log(checkedRows);

            //var options = $('#myDg').iDatagrid('options');
            //var selectedRow = $('#myDg').iDatagrid('getSelected');
            //console.log(selectedRow);

            // 提交参数查询表格数据
            //$('#productDg').iDatagrid('reload', {
            //    name: $('#name').iTextbox('getValue'),
            //    code: $('#code').iTextbox('getValue')
            //});
        }
    }
</script>

<!--全局变量和公共方法-->
<script>

    // 处理添加和编辑的时候load之后调用的方法
    function addOrEditLoad(type,uuid) {
        if (type == "add") {
        }

        if (type == "edit") {
        }
    }

    // 保存时用户的自定义验证
    function userValidate() {
        //var myFormProductGUIDValue = $("#myFormProductGUID").iCombobox("getValue");
        //if (myFormProductGUIDValue.length != 36) {
        //    layer.msg("@L("请选择对应产品")");
        //    return false;
        //}

        return true;
    }
</script>

<!--表格操作-->
<script>
// 定义初始化过滤条件
var myDgInitFilter = null;
//if (queryObj.classGUID) {
//    myDgInitFilter = {
//    Type: "and",
//    conditions: [{
//        Attribute: "classGUID",
//        Datatype: "uniqueidentifier",
//        Operatoer: "eq",
//        Value: queryObj.classGUID
//    }]
//   };
//}

// 获取过滤条件
function getFilters() {
    var initFilter = null;
    var filter = $.ei.getFilters(); // 获取界面查询条件

    // 如果有初始化条件那么把初始化的条件加上去
    if (myDgInitFilter && myDgInitFilter.conditions) {
        initFilter =  _.cloneDeep(myDgInitFilter);
        if (filter) {
            initFilter.conditions = _.union(filter.conditions, myDgInitFilter.conditions);
        }
    } else if (filter) {
        initFilter = filter; // 没有初始化条件 那么用查询的条件
    }

    if (initFilter) {
        return JSON.stringify(initFilter);
    } else {
        return null;
    }
}

// 表格查询
function searchQuery() {
    var param = $('#myDg').iDatagrid('options').queryParams;
    param.filter = getFilters();
    $('#myDg').iDatagrid('load', param);
}

$(function () {
    $("#mySearchForm").show();
    // 初始化表格
    var dg = $('#myDg').iDatagrid({
    url: '/api/services/app/FWCompany/GetGridDto',
    fitColumns: true,
    queryParams: {
        order: 'CreateTime  desc',
        viewName: 'view_FW_Company',
        filter: getFilters()
    },
    columns: [
        [
            {
                field: 'id',
                title: 'id',
                checkbox: true,
                datatype: 'uniqueidentifier',
            },

            {
                field: 'companyName',
                title: '@L("企业名称")',
                width: 120,
                sortable: true,
                datatype: 'nvarchar',
            },

            {
                field: 'companyDesc',
                title: '@L("企业介绍")',
                width: 120,
                sortable: true,
                datatype: 'nvarchar',
            },

            {
                field: 'companyLogoUrl',
                title: '@L("企业Logo")',
                width: 120,
                sortable: true,
                datatype: 'nvarchar',
                formatter: $.ei.imgFormatter,
            },

            //{
            //    formatter: operateFormatter,
            //    field: 'createTime',
            //    title: '@L("操作")',
            //    sortable: true,
            //    width: 100
            //}
        ]
    ],
    onDblClickRow: function (a, b) {
        @if (currentUserInfo.IsHaveRights("FW_Company", "02")){
        <text>
        openEditDiag(b.id);
        </text>}
        else{
        <text>
        openDetailDiag(b.id);
        </text>}
    },
    frozenColumns: [[

    ]],
    filter: [
        {
            field: 'companyName',
            type: 'textbox',
            op: ['contains', 'equal', 'notequal', 'endwith', 'beginwith']
        },

        {
            field: 'companyDesc',
            type: 'textbox',
            op: ['contains', 'equal', 'notequal', 'endwith', 'beginwith']
        },

        {
            field: 'companyLogoUrl',
            type: 'textbox',
            op: ['contains', 'equal', 'notequal', 'endwith', 'beginwith']
        },

    ]
});
})

function operateFormatter(value, row, index) {
    var htmlStr = '<button class="layui-btn layui-btn-xs" onclick="openDetailDiag(\'{0}\')">查看</button>'.format(row.id);
    @if (currentUserInfo.IsHaveRights("FW_Company", "02"))
    {
        <text>
            htmlStr += '<button class="layui-btn layui-btn-xs" onclick="openEditDiag(\'{0}\')">编辑</button>'.format(row.id);
        </text>
    }

    @if (currentUserInfo.IsHaveRights("FW_Company", "03"))
    {
        <text>
            htmlStr += '<button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteRow(\'{0}\')">删除</button>'.format(row.id);
        </text>
    }

    return htmlStr;
}
</script>

<!--按钮相关-->
<script>
// 设置权限
function setRight() {
var checkedRows = $('#myDg').iDatagrid('getSelected');
var uuid = checkedRows.id;
if (!uuid) {
    $.iMessager.alert("提示", "请选择一行");
    return;
}
var $editDialog = $('<form id="mysetRightDialog"></form>'); // 创建form表单元素
$editDialog.iDialog({
    title: '@L("设置权限")',
    width: 850,
    height: 550,
    closed: false,
    cache: false,
    href: '/FW/FWStandardRole2Action/SetRightIndex?standardRoleGUID={0}&&isBuSet=1'.format(uuid),
    buttons: [{
        text: '@L("保存")',
        iconCls: 'fa fa-save',
        btnCls: 'topjui-btn-save',
        handler: function () {
            $.iMessager.progress({ 'text': '@L("保存中…")' });
            var applicationGUID = $("#myFormApplicationGUID").val();
            var chkActionIds = [];
            var chkBox = $("#SetRightIndexTabs").find("input[name=rights]:checked");
            $.each(chkBox, function (index, item) {
                if (item.checked) {
                    chkActionIds.push(item.value);
                }
            });

            var data = {
                companyGUID: uuid,
                actionIds: chkActionIds,
                applicationGUID: applicationGUID
            }
            var options = {
                url: '/api/services/app/FWCompany2Action/BatchSaveBuAction',
                data: data
            };

            var success = function (result) {
                $.iMessager.show({ title: '@L("消息")', msg: '@L("设置成功")', timeout: 2000, showType: 'slide' });// '消息窗口'组件
                $('#mysetRightDialog').iDialog('close');// 销毁dialog面板
            }
            abp.ajax(options).done(success);
        }
    },
    {
        text: '@L("关闭")',
        iconCls: 'fa fa-close',
        btnCls: 'topjui-btn-close',
        handler: function () {
            $('#mysetRightDialog').iDialog('close');// 销毁dialog面
        }
    }],
    onLoad: function () {
    }
});
}

function oepnAddDiag() {
    var $editDialog = $('<form id="myFormDialog"></form>'); // 创建form表单元素
    $editDialog.iDialog({
        title: '@L("新增企业表")',
        width: 750,
        height: 550,
        closed: false,
        cache: false,
        maximized: false, // 初始化是否最大化
        href: '/FW/FWCompany/FWCompanyEdit?mode=1',
            buttons: [{
            text: '@L("保存")',
            iconCls: 'fa fa-save',
            btnCls: 'topjui-btn-blue',
            handler: function () {
                saveDate("saveAndClose");
            }
        },
        {
            text: '@L("保存&新增")',
            iconCls: 'fa fa-save',
            btnCls: 'topjui-btn-blue',
            handler: function () {
                saveDate("saveAndNew");
            }
        },
        //{
        //    text: '@L("保存&关闭")',
        //    iconCls: 'fa fa-save',
        //    btnCls: 'topjui-btn-blue',
        //    handler: function () {
        //        saveDate("saveAndClose");
        //    }
        //},
        {
            text: '@L("关闭")',
            iconCls: 'fa fa-close',
            btnCls: 'topjui-btn-red',
            handler: function () {
                $('#myFormDialog').iDialog('close');// 销毁dialog面
            }
        }],
        onLoad: function () {
            addOrEditLoad("add");
            formAddInit($editDialog);
        }
    });
}

function formAddInit(formDialog) {
    var result = {
        studentName:'123'
    };
    // formDialog.iForm('load', result);

    //var options = {
    //    url: '/api/services/app/OADayReport/GetViewDto',
    //    maskJqSelect: '#myFormDialog'
    //};

    //var success = function (result) {
    //    $editDialog.iForm('load', result);
    //}

    //abp.ajax(options).done(success);
}

function openEditDiag(uuid) {
    if (!uuid) {
        var selectedRow = $('#myDg').iDatagrid('getSelected');
        uuid = selectedRow.id;
    }
    var $editDialog = $('<form id="myFormDialog"></form>'); // 创建form表单元素
    $editDialog.iDialog({
        title: '@L("编辑企业表")',
        width: 750,
        height: 550,
        closed: false,
        cache: false,
        maximized: false, // 初始化是否最大化
        href: '/FW/FWCompany/FWCompanyEdit?uuid=' + uuid+'&mode=2',
        // modal: true,
        buttons: [
        @if (currentUserInfo.IsHaveRights("FW_Company", "02")) {
        <text>
        {
            text: '@L("保存")',
            iconCls: 'fa fa-save',
            btnCls: 'topjui-btn-blue',
            handler: function () {
                saveDate("saveAndClose");
            }
        },
        </text>}
        //{
        //    text: '@L("保存&关闭")',
        //    iconCls: 'fa fa-save',
        //    btnCls: 'topjui-btn-blue',
        //    handler: function () {
        //        saveDate("saveAndClose");
        //    }
        //},
        {
            text: '@L("关闭")',
            iconCls: 'fa fa-close',
            btnCls: 'topjui-btn-red',
            handler: function () {
                $('#myFormDialog').iDialog('close');// 销毁dialog面
            }
        }],
        onLoad: function () {
            addOrEditLoad("edit",uuid);
            var data = { 'id': uuid };
            var options = {
                url: '/api/services/app/FWCompany/GetViewDto',
                maskJqSelect: '#myFormDialog',
                data:data
            };

            var success = function (result) {
                $editDialog.iForm('load', result);

                // 绑定combox
                $editDialog.find('[data-toggle="topjui-combobox"]').each(function (b) {
                    var c = $(this);
                    var opt = getOptionsJson(c);
                    if (opt.queryParams.viewName) {
                        c.iCombobox(opt);
                    }
                });

                // 在这里进行绑定UeEditor
                $editDialog.find('[data-toggle="topjui-ueditor"]').each(function (b) {
                    var c = $(this);
                    var name = c.attr('name');
                    var opt = getOptionsJson(c);
                    var id = opt.id;
                    var ue = UE.getEditor(id);
                    ue.ready(function () {
                        ue.setContent(result[name]);
                    });
                });

                @if (!currentUserInfo.IsHaveRights("FW_Company", "02")) {
                <text>
                $editDialog.iForm('readonly');
                </text>}
            }

            abp.ajax(options).done(success);
        }
    });
}

// operate表示操作类型有 save saveAndClose saveAndNew
function saveDate(operate) {
    // 1. 显示进度条（提交时请使用进度条 或者 禁用'提交'按钮，防止因为网络延迟用户重复提交）
    $.iMessager.progress({ 'text': '@L("保存中...")' });
    var isValid = $('#myFormDialog').iForm('validate'); //  提交数据表单数据时进行表单验证
    var isUserValid = userValidate();
    if (!isValid || !isUserValid) {
        layer.msg('@L("格式不正确,请填写对应的必填项!")');
        $.iMessager.progress('close');  // 如果表单是无效的则隐藏进度条
        return;
    }

    var data = $.dm.parseQueryString($('#myFormDialog').serialize());
    var options = {
        url: '/api/services/app/FWCompany/CreateByDto',
        data: data
    };

    // 有ID就是更新
    if (data.id) {
        options.url = '/api/services/app/FWCompany/UpdateByDto'
    }
    var success = function (result) {
        $("#myDg").iDatagrid('reload'); // 刷新下表格数据
        $('#myFormDialog').iForm('load', { id: result.id });
        // 保存并关闭
        if (operate === 'saveAndClose') {
            $.iMessager.show({ title: '@L("我的消息")', msg: '@L("保存成功")', timeout: 2000, showType: 'slide' });// '消息窗口'组件
            $('#myFormDialog').iDialog('close');// 销毁dialog面板
        } else if (operate === 'saveAndNew') {
            // 保存新增重置form
            $("#uuid").val(""); // 清空GUID
            $('#myFormDialog').iForm('reset');
            // UE.getEditor('myFormDayReportDesc').setContent('');
            formAddInit($('#myFormDialog'));
            layer.msg("@L("保存成功")");
        } else {
            layer.msg("@L("保存成功")");
        }
    }
    abp.ajax(options).done(success);
}

function openDetailDiag(uuid) {
        if (!uuid) {
        var selectedRow = $('#myDg').iDatagrid('getSelected');
        uuid = selectedRow.id;
    }
    var $editDialog = $('<form id="myDetailDialog"></form>'); // 创建form表单元素
    $editDialog.iDialog({
        title: '@L("查看企业表")',
        width: 750,
        height: 550,
        closed: false,
        cache: false,
        href: '/FW/FWCompany/FWCompanyDetail?uuid=' + uuid,
        buttons: [ {
            text: '@L("关闭")',
            iconCls: 'fa fa-close',
            btnCls: 'topjui-btn-red',
            handler: function () {
                $('#myDetailDialog').dialog('close');// 销毁dialog面
            }
        }],
        onLoad: function () {
            var data = { 'id': uuid };
            var options = {
                url: '/api/services/app/FWCompany/GetViewDto',
                maskJqSelect: '#myDetailDialog',
                data : data
            };

            var success = function (result) {
                    $("#FWCompanyDetailTableTemplate").tmpl(result)
                    .appendTo("#FWCompanyDetailTable");
            }
            abp.ajax(options).done(success);
        }
    });
}

// 删除行数据
function deleteRow(id) {
    $.messager.confirm("@L("提示")", "@L("确定要删除该条数据吗?")", function (result) {
        if (result) {
            $.iMessager.progress({ 'text': '@L("处理中...")' });
            var data={'id':id};
            var options = {
                url: '/api/services/app/FWCompany/DeleteByDto',
                maskJqSelect: '#myDg',
                data: data
            };

            var success = function (result) {
                $("#myDg").iDatagrid('reload');// 刷新下表格数据
                $.iMessager.show({ title: '@L("我的消息")', msg: '@L("删除成功")', timeout: 2000, showType: 'slide' });// '消息窗口'组件
            }

            abp.ajax(options).done(success);
        }
    })
}

// 自定义方法
function myQuery() {
    alert("123");
    // 选择一行
    $('#myDg').datagrid('selectRow', 1);
    // 提示信息
    //$.iMessager.alert('自定义方法', '自定义方法被执行了！', 'messager-info');

    //var checkedRows = $('#productDg').iDatagrid('getChecked');
    //console.log(checkedRows);

    //var options = $('#myDg').iDatagrid('options');
    //var selectedRow = $('#myDg').iDatagrid('getSelected');
    //console.log(selectedRow);

    // 提交参数查询表格数据
    //$('#productDg').iDatagrid('reload', {
    //    name: $('#name').iTextbox('getValue'),
    //    code: $('#code').iTextbox('getValue')
    //});
}
</script>

